import {ActionReducer, Action, combineReducers} from "@ngrx/store";

const actionTypes = []
function checkType(name) {
  if (actionTypes.indexOf(name) >= 0) {
    throw new Error(`the action type '${name}' has defined`)
  } else {
    actionTypes.push(name)
    return name
  }
}

export const INCREMENT = checkType('INCREMENT')
export const DECREMENT = checkType('DECREMENT')
export const RESET = checkType('RESET')
export const ADD_INFO = checkType('ADD_INFO')
export const SUBTRACT_HOUR = checkType('SUBTRACT_HOUR')

export const counterReducer: ActionReducer<number> = (state: number = 0, action: Action) => {
  switch (action.type) {
    case INCREMENT:
      return state + 1

    case DECREMENT:
      return state - 1

    case RESET:
      return 0

    default:
      return state
  }
}

export const operateReducer: ActionReducer<number> = (state: number = 0, action: Action) => {
  switch (action.type) {
    case INCREMENT:
    case DECREMENT:
    case RESET:
      return state + 1
    default:
      return state
  }
}

export const infoReducer = (state = {}, action) => {
  switch (action.type) {
    case ADD_INFO:
      return Object.assign({}, state, action.payload)
    default:
      return state;
  }
}

const person = (state = {name: 'unknown'}, action) => {
  switch (action.type) {
    case 'ADD_INFO':
      return Object.assign({}, state, action.payload)
    default:
      return state;
  }
}

const hoursWorked = (state = 0, action) => {
  switch (action.type) {
    case ADD_INFO:
      return state + 1;
    case SUBTRACT_HOUR:
      return state - 1;
    default:
      return state;
  }
}

export const combinedReducer = combineReducers({
  person: person,
  hours: hoursWorked,
  more: combineReducers({person})
})
